<?php


namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Response;

/**
 * wx微信登录6661..
 *
 * Class YzyController
 *
 * @package App\Http\Controllers
 */
define("TOKEN_jc", "wechat");
//define("appID", "wx03fc75e6836cd361");
//define("secret", "5712d2e3f8eb6981405a46c67dccdf10");
define("appID", "wx497d134c5cefcfec");
define("secret", "eba010e11ddd65c956fdef691a5243a0");
class Wx extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }



    public function index(){
        $request = $this->request->post();
        $hbcode=$request['hbcode'];
        $appID=appID;
        $secret = secret;
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appID.'&secret='.$secret),true)['access_token'];
//        return $access_token; //返回页面

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";

        $ch = curl_init();

        $data = json_encode([
            'expire_seconds' => '604800',
//            'action_name' => 'QR_SCENE',//临时.
            'action_name' => 'QR_STR_SCENE',//永久
            'action_info' => [
                'scene' =>[
//                    'scene_id' => '10000',//永久二维码时最大值为100000
                    'scene_str' =>$hbcode?$hbcode: 'qrscene_100000000',//EventKey-长度限制为1到64，仅永久二维码支持此字段-场景id-前端请求接口给一个随机字符串64位内-回调-接口返回参数-用这个验证是不是本页面发出的二维码-通过验证，则账号1登录成功
                ],
            ]

        ]);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');

        curl_setopt($ch, CURLOPT_URL,$url);

        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(

            'Content-Type: application/json',

            'Content-Length: ' . strlen($data)

        ));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里，那加上这句。

        $res = curl_exec($ch);
        $res=json_decode($res);
//        dd($res);




        $ticket=  urlencode($res->ticket);

        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);

        echo "<img src=".$url." width='220' height='220'/>";
//        return $res->ticket; //返回页面.


    }




    public function _getWxAccessToken(){
        $appID=appID;
        $secret = secret;
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appID.'&secret='.$secret),true)['access_token'];
        return $access_token;
    }
    //临时二维码
    public function getQrls()
    {
        $accessToken = $this->_getWxAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$accessToken}";
        $postArr =  [
            "action_name" => "QR_SCENE",
            "expire_seconds" => 604800,
            "action_info" => [
                'scene' => ['scene_id' => 2000],
            ],
        ];

        $postJson = json_encode($postArr);
        $res = $this->ch($url, 'post', 'json', $postJson);

        $ticket = $res['ticket'];
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);

        echo "<img src=".$url.">";

    }

    //永久二维码
    public function getQryj()
    {
        $accessToken = $this->_getWxAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$accessToken}";
        $postArr =  [
            "action_name" => "QR_LIMIT_SCENE",
            "action_info" => [
                'scene' => ['scene_id' => 3000],
            ],
        ];

        $postJson = json_encode($postArr);
        $res = $this->ch($url, 'post', 'json', $postJson);

        $ticket = $res['ticket'];
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);

        echo "<img src=".$url.">";
    }

    //url请求
    private function ch($url, $type='get', $res='json', $arr='')
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }

        $cnt = curl_exec($ch);
        if (curl_errno($ch)) {
            return;
        }

        curl_close($ch);

        if ($res == 'json') {
            return json_decode($cnt, true);
        }

        return $cnt;
    }









    //基础信息，提交验证token ks
    public function valid()

    {

        $echoStr = $_GET["echostr"];


        //valid signature , option

        if($this->checkSignature()){

            echo $echoStr;

            exit;

        }

    }
    private function checkSignature()

    {

        $signature = $_GET["signature"];

        $timestamp = $_GET["timestamp"];

        $nonce = $_GET["nonce"];


        $token = TOKEN_jc;

        $tmpArr = array($token, $timestamp, $nonce);

        sort($tmpArr);

        $tmpStr = implode( $tmpArr );

        $tmpStr = sha1( $tmpStr );


        if( $tmpStr == $signature ){

            return true;

        }else{

            return false;

        }

    }
    //基础信息，提交验证token js





//用户行为(扫码或关注)之后接收微信回调
    /**
     * 微信事件推送接收方法-wxhd
     */
    public function responseMsg()
    {
//        dd(123);
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            // 微信消息类型
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE) {
                case "text":
                    // 文本消息
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    // 事件推送
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
            exit;
        }
    }
//处理微信回调(消息或事件)
    /**
     * 微信文本消息
     * @param $postObj
     */
    public function handleText()
    {
        $postObj = $this->request->post();
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty($keyword)) {
            $msgType = "text";
            $contentStr = "欢迎您关注";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        } else {
            echo "请输入...";
        }
    }
    /**
     * 获取时间消息并解析相应参数
     * 提供数据简单推送(自动回复)
     * @param $object
     *
     * @return string
     */
    public function handleEvent()
    {
        $object = $this->request->post();
        $contentStr = "";
        switch ($object->Event) {
            case "subscribe":
                $contentStr = "感谢您关注";
                $openid = (string)$object->FromUserName; //数据类型转换为字符串
//                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_1232313这种类型
                $this->createuserinfo($openid,0,$object);//获取用户信息
                break;
            case "SCAN":

                $contentStr = "您已关注过，谢谢！";
                $openid = (string)$object->FromUserName; //数据类型转换为字符串
//                $refer_id = explode('_', $object->EventKey);

                //$object->EventKey返回的是qrsence_12213213这种类型
                $this->createuserinfo($openid, 1,$object);//获取用户信息

                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }

    public function responseText($postObj, $contentStr)
    {


        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        $msgType = "text";
        $contentStr = "扫码成功";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
    }
//获取用户详细信息
//在微信回调方法可获取到用户openid
//结合access_token即可获取到用户详细信息

    /**
     * 根据openid查询用户-登录-
     * @param $openid
     * @param $refer_id
     * @param $object--
     */
//    $openid, $refer_id,$object
    public function createuserinfo($openid, $refer_id,$object)
    {

        $EventKey = (string)$object->EventKey; //数据类型转换为字符串
        $user = DB::table('user_wx_log')
            ->where('openid', $openid)
            ->get();
        if ($user->count()){
//            有值-登录

            $data=[
                'updated_at'=>date('Y-m-d H:i:s'),//更新登录时间
                'hbcode' => $EventKey,//更新机器码
                'status_dl' => 1,//更新扫码状态-状态：0-未扫码、1-已扫码
            ];
            $user = DB::table('user_wx_log')
                ->where('openid', $openid)
                ->update($data);



        }else{
//            没值-新建user_wx_log--绑定-原有账号，根据username手机号-


            $data_add=[
                'created_at'=>date('Y-m-d H:i:s'),//更新登录时间
                'updated_at'=>date('Y-m-d H:i:s'),//更新登录时间
                'hbcode' => $EventKey,//更新机器码
                'status_dl' => 1,//更新扫码状态-状态：0-未扫码、1-已扫码
                'openid' => $openid,
            ];
            $id = DB::table('user_wx_log')->insertGetId($data_add);



//             return Response::json(['code' => '1','data' => [],'message' => '登录失败,未注册，请先绑定账号','hbcode'=>$EventKey]);

        }
    }
    /**
     * 根据username 的手机号查询用户-绑定openid
     * @param $request
     */
    public function addopenid()
    {
        $request = $this->request->post();
        $username = trim($request['username']);
        $hbcode=$request['hbcode'];
        $user = DB::table('user_wx_log')
            ->where('hbcode', $hbcode)
            ->get();
        if ($user->count()){
        }else{
            return Response::json(['code' => '0','data' => [],'message' => '未登录，请先登录','hbcode'=>$hbcode]);
        }

        $user_openid = DB::table('user')
            ->where('wechat', $user[0]->openid)
            ->get();
        if ($user_openid->count()){
            return Response::json(['code' => '0','data' => [],'message' => '绑定失败，请先解绑','hbcode'=>$hbcode]);
        }else{
            $data=[
                'wechat'=>$user[0]->openid,
                'jiqi_code'=>$user[0]->hbcode,
            ];
            $user_up = DB::table('user')
                ->where('username', $username)
                ->update($data);
            $user_openid = DB::table('user')
                ->where('username',$username)
                ->get();
            $data_wx=[
                'status'=>1,
                'user_id'=>$user_openid[0]->id,
            ];
            $user_wx_log_up = DB::table('user_wx_log')
                ->where('hbcode', $hbcode)
                ->update($data_wx);
            return Response::json(['code' => '1','data' => [],'message' => '绑定成功']);
        }

    }

    /**
     * 根据username 的手机号查询用户-解绑openid
     * @param $request
     */
    public function deopenid()
    {        $request = $this->request->post();
        $username=$request['username'];
        $hbcode=$request['hbcode'];
        $user = DB::table('user')
            ->where('username', $username)
            ->get();
        if ($user->count()){
        }else{
            return Response::json(['code' => '0','data' => [],'message' => '未登录，请先登录','hbcode'=>$hbcode]);
        }
//        dd($user[0]);
        if ($user[0]->wechat){
            $data=[
                'wechat'=>'',
            ];
            $user = DB::table('user')
                ->where('username', $username)
                ->update($data);
            return Response::json(['code' => '1','data' => [],'message' => '解绑成功','hbcode'=>$hbcode]);
        }else{
            return Response::json(['code' => '0','data' => [],'message' => '未绑定']);
        }


    }

    /**
     * 根据hbcode机器码查询用户
     * @param $request
     */

    public function gethb()
    {
        $request = $this->request->post();
        $hbcode=$request['hbcode'];
        $user_wx_log = DB::table('user_wx_log')
            ->where('hbcode', $hbcode)
            ->get();
        $user = DB::table('user')
            ->where('jiqi_code', $hbcode)
            ->get();


//            有值-登录
        if ($user_wx_log->count()){
            if($user_wx_log[0]->status_dl==1){

                if ($user->count()){
//                    有值-登录
                    $request['username']=$user[0]->username;
                    $request['hbcode']=$hbcode;
                    $obj =  new LoginController;
                    $lsit=  $obj->wx_login($request);
                    //扫码只能登录一次-
                    $data_wx=[
                        'status_dl'=>0,
                    ];
                    $user_wx_log_up = DB::table('user_wx_log')
                        ->where('hbcode', $hbcode)
                        ->update($data_wx);
                    return $lsit;

                }else{
//            没值-注册
//                    dd($user_wx_log);
                    $data_op = [
                        'openid'  => $user_wx_log[0]->openid,
                    ];
                    return Response::json(['code' => '0','data' => $data_op,'message' => '登录失败,未注册，请先注册','hbcode'=>$hbcode]);
                }

            }else{
                return Response::json(['code' => '0','data' => [],'message' => '登录过一次,请再次扫码','hbcode'=>$hbcode]);
            }
        }else{
            return Response::json(['code' => '0','data' => [],'message' => '未扫码','hbcode'=>$hbcode]);
        }



    }

    /**
     * 根据openid 注册user
     * @param $request
     */
    public function adduser()
    {
        $request = $this->request->post();
        $openid = trim($request['openid']);
        $user = DB::table('user_wx_log')
            ->where('openid', $openid)
            ->get();

        $user_openid = DB::table('fa_g_user')
            ->where('wechat', $openid)
            ->get();
        if ($user_openid->count()){
            return Response::json(['code' => '0','data' => [],'message' => '绑定失败，请先解绑']);
        }else{
            $data=[
                'wechat'=>$user[0]->openid,
                'jiqi_code'=>$user[0]->hbcode,
            ];

            $data_add=[
                'created_at'=>date('Y-m-d H:i:s'),//更新登录时间
                'updated_at'=>date('Y-m-d H:i:s'),//更新登录时间
                'username' => $openid,//更新机器码
                'jiqi_code' => $user[0]->hbcode,//更新扫码状态-状态：0-未扫码、1-已扫码
                'wechat' => $openid,
            ];
            $id = DB::table('fa_g_user')->insertGetId($data_add);


            $data_wx=[
                'status'=>1,
                'user_id'=>$id,
            ];
            $user_wx_log_up = DB::table('user_wx_log')
                ->where('openid', $openid)
                ->update($data_wx);
            return Response::json(['cdoe' => '1','data' => [],'message' => '注册成功']);
        }

    }



}
